import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xmshop/app/models/plist_model.dart';
import 'package:xmshop/app/services/httpsClient.dart';

class ProductListController extends GetxController {
  ScrollController scrollController = ScrollController();
  GlobalKey<ScaffoldState> scaffoldGlobalKey = GlobalKey<ScaffoldState>();
  RxList<PlistItemModel> plist = <PlistItemModel>[].obs;
  bool canRequest = true; // 是否能发起请求
  RxBool hasMore = true.obs; // 是否还有更多数据
  int page = 0;
  int pageSize = 8;

  HttpsClient httpsClient = HttpsClient();

  // 排序
  String sort = "";

  /*二级导航数据*/
  List subHeaderList = [
    {
      "id": 1,
      "title": "综合",
      "fields": "all",
      "sort":
          -1, // 排序     升序：price_1     {price:1}        降序：price_-1   {price:-1}
    },
    {"id": 2, "title": "销量", "fields": 'salecount', "sort": -1},
    {"id": 3, "title": "价格", "fields": 'price', "sort": -1},
    {"id": 4, "title": "筛选"}
  ];
  //二级导航选中判断
  RxInt selectHeaderId = 1.obs;
  //主要解决的问题是排序箭头无法更新
  RxInt subHeaderListSort = 0.obs;

  String? keyword = Get.arguments["keyword"];
  String? cid = Get.arguments["cid"];
  String apiUrl = "";

  @override
  void onInit() {
    super.onInit();
    getPlistData();
    initScrollController();
  }

  // 监听滚动条事件
  void initScrollController() {
    scrollController.addListener(() {
      // scrollController.position.pixels; 滚动条下拉的高度
      // scrollController.position.maxScrollExtent; 页面的高度
      if (scrollController.position.pixels >
          scrollController.position.maxScrollExtent - 20) {
        // 滚动到页面底部了
        getPlistData();
      }
    });
  }

  // 二级导航改变的时候触发的方法
  void subHeaderChange(id) {
    if (id == 4) {
      selectHeaderId.value = id;
      // 弹出侧边栏
      scaffoldGlobalKey.currentState!.openEndDrawer();
    } else {
      selectHeaderId.value = id;
      // 改变排序 sort=price_-1 sort=price_1
      sort =
          "${subHeaderList[id - 1]["fields"]}_${subHeaderList[id - 1]["sort"]}";
      // 改变状态
      subHeaderList[id - 1]["sort"] = subHeaderList[id - 1]["sort"] * -1;
      // 作用：更新状态
      subHeaderListSort.value = subHeaderList[id - 1]["sort"];
      // 重置page
      page = 1;
      // 重置数据
      plist.value = [];
      // 重置hasMore
      hasMore.value = true;
      // 滚动条回到顶部
      scrollController.jumpTo(0);
      // 重新请求接口
      getPlistData();
    }
  }

  @override
  void onClose() {
    super.onClose();
    scrollController.removeListener(() {});
  }

  // 获取商品列表数据
  void getPlistData() async {
    if (canRequest && hasMore.value) {
      canRequest = false;
      page++;

      if (keyword != null) {
        apiUrl =
            "api/plist?keyword=$keyword&page=$page&pageSize=$pageSize&sort=$sort";
      } else {
        apiUrl = "api/plist?cid=$cid&page=$page&pageSize=$pageSize&sort=$sort";
      }

      print("url is $apiUrl");

      var response = await httpsClient.get(apiUrl);

      if (response != null) {
        var plistTemp = PlistModel.fromJson(response.data);
        // 注意：上拉加载更多要拼接数据
        plist.addAll(plistTemp.result!);
        canRequest = true;
        if (plistTemp.result!.length < pageSize) {
          hasMore.value = false;
        }
        update();
      }
    }
  }
}
